<template>
    <div class="console"  v-loading="loading" >
        <div class="console-tools">
            <div class="console-tools-item">
                <el-button text  @click="saveQueryScript">
                    <el-icon size="16"><Document /></el-icon>
                    保存
                </el-button>
            </div>
            <div class="console-tools-item">
                <el-button text @click="runConsoleScript">
                    <el-icon size="16" color="#529b2e">
                        <VideoPlay/>
                    </el-icon>
                    运行
                </el-button>
            </div>
        </div>
        <div class="console-edit" :style="showType===1||showType===2?'height: calc(99vh - (99vh * 0.55) - 220px);':'height: calc(99vh - 150px);'">
            <AceEditor  @getEditorInstance="getEditorInstance"/>
        </div>
        <div class="console-data" v-if="showType===1">
            <div class="console-data-tips">
                <div>只读</div>
                <div>查询结果共计{{tableData.length}}条记录</div>
            </div>
            <el-table :data="tableData" border height="calc(99vh * 0.55)" highlight-current-row  @row-click="tableClickRow">
                <el-table-column type="index" width="50" fixed >
                    <template #default="scope">
                        <div style="width: 100%;display: flex;justify-content: flex-start;">
                            <div v-if="selectRowIndex===(scope.$index+1)"><el-icon size="18"><CaretRight /></el-icon></div>
                            <div>{{initIndex(scope.$index)}}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column :key="field.COLUMN_NAME" :label="field.COLUMN_NAME"
                                 :min-width="getColumnWidth(field.COLUMN_NAME)" :prop="field.COLUMN_NAME" show-overflow-tooltip
                                 v-for="field in fieldData">
                    <template #default="scope">
                        {{getDateFormat(field,scope.row[field.COLUMN_NAME])}}
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="console-data" v-if="showType===2">

        </div>
    </div>
    <el-dialog  v-model="saveVisible"  title="Tips"  width="500">
        <el-form :model="formData" label-width="auto" style="max-width: 600px">
            <el-form-item :label="keyInfo"  v-for="keyInfo in keyList">
                <el-input v-model="formData[keyInfo]" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="saveVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRunScript">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="MysqlTableFunctionInfo">
    import AceEditor from '@/components/aceEditor'
    import {formatDate,formatTime} from "@/utils/dateUtils";
    import {format} from 'sql-formatter';
    const {proxy} = getCurrentInstance();
    const consoleData=reactive({
        dataBaseMeta:[],
        showType:0,
        fieldData:[],
        tableData:[],
        tableCount: 0,
        loading:false,
        selectRowIndex:0,
        aceEditorInstance:null,
        connectionInfo:null,
        saveVisible:false,
        formData:{},
        keyList:[],
    })

    const {dataBaseMeta,showType,fieldData,tableData,tableCount,loading,selectRowIndex,aceEditorInstance,connectionInfo,saveVisible,formData,keyList} =toRefs(consoleData)

    function getEditorInstance(aceEditor) {
        aceEditorInstance.value = aceEditor
        if(!proxy.$route.query.SPECIFIC_NAME){
            let top="CREATE DEFINER = CURRENT_USER PROCEDURE `NewProc`( )"
            aceEditorInstance.value.session.setValue( `${top}\r\nBEGIN\r\n#Routine body goes here...\r\nEND;`)
        }
    }

    function tableClickRow(row,column,event){
        selectRowIndex.value=(tableData.value.indexOf(row)+1)
    }

    function initConnection() {
        if(connectionInfo.value==null){
            let connect =proxy.$appStore.connectList.find(row=>row.id===(proxy.$route.query.connectId*1));
            connect.database=proxy.$route.query.databaseName
            connectionInfo.value=connect
        }
    }


     function initParams() {
        initConnection()
        let query = proxy.$route.query;
        if (Object.keys(query).length > 0) {
            if(proxy.$route.query.SPECIFIC_NAME){
                let params = {}
                params.databaseKey = proxy.$route.query.databaseName
                params.specificName = proxy.$route.query.SPECIFIC_NAME
                keyList.value=[]
                proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.getFunctionParamsList, connectionInfo.value, params).then(res => {
                    let paramsStr = ''
                    let array = []
                    res.data.dataList.forEach(row => {
                        array.push(row.PARAMETER_NAME + ' ' + row.DATA_TYPE.toUpperCase())
                        keyList.value.push(row.PARAMETER_NAME)
                    })
                    if (array.length > 0) {
                        paramsStr = array.join(",")
                    }
                    let top = 'CREATE ' + query.SECURITY_TYPE + "=`" + query.DEFINER.split("@").join("`@`") + "` " + query.ROUTINE_TYPE + " `" + query.ROUTINE_NAME + "` (" + paramsStr + ")"
                    aceEditorInstance.value.session.setValue( `${top}\r\n${query.ROUTINE_DEFINITION}`)
                })
            }
        }
    }

    function runConsoleScript(){
        if(keyList.value.length<1){
            let script="CALL "+proxy.$route.query.ROUTINE_NAME+"()"
            run(script)
        }else {
            saveVisible.value=true
        }
    }

    function confirmRunScript() {
        saveVisible.value=false
        let paramsArray=[]
        Object.keys(formData.value).forEach(key=>paramsArray.push(formData.value[key]))
        let script="CALL "+proxy.$route.query.ROUTINE_NAME+"("+paramsArray.join(",")+")";
        run(script)
    }

    function run(script) {
        let params={}
        params.runScript=script
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole,connectionInfo.value,params).then(res=>{
            if(res.code===200){
                if(Array.isArray(res.data.dataList)){
                    showType.value=1//列表
                    tableData.value=res.data.dataList
                    fieldData.value=res.data.fieldList
                }else {
                    showType.value=2//结果
                }
            }else{
                proxy.$modal.alertError(res.message)
            }
        })
    }

    function formatConsoleInput() {
        aceEditorInstance.value.session.setValue(format(aceEditorInstance.value.session.getValue(), {language: 'mysql'}))
    }



    function getDateFormat(field,fieldValue){
        if(field.DATA_TYPE==='datetime'||field.DATA_TYPE==='timestamp'){
            return formatTime(fieldValue);
        }
        if(field.DATA_TYPE==='date'){
            return formatDate(fieldValue);
        }
        return fieldValue;
    }

    function initIndex(index) {
        let rowIndex = index + 1
        if(tableCount.value===0){
            loading.value = false
        }else if(rowIndex===tableCount.value){
            loading.value = false
        }
        return rowIndex;
    }

    function getColumnWidth(columnText) {
        if (columnText.length > 20) {
            return 180;
        }
        if (columnText.length > 10) {
            return 160;
        }
        if (columnText.length > 5) {
            return 120;
        }
        return 80;
    }

    function saveQueryScript() {
        let script = aceEditorInstance.value.session.getValue()
        let params={}
        params.runScript="DROP PROCEDURE IF EXISTS `"+proxy.$route.query.ROUTINE_SCHEMA+"`.`"+proxy.$route.query.ROUTINE_NAME+"`"
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole,connectionInfo.value,params)
        params.runScript=script
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole,connectionInfo.value,params).then(res=>{
            if(res.code===200){
                proxy.$modal.msgSuccess("保存成功")
            }else{
                proxy.$modal.alertError(res.message)
            }
        })
    }

    const handleEvent = async (event) => {
        if (event.keyCode === 83) {
            if (event.ctrlKey && event.code === 'KeyS') {
                event.preventDefault()
                event.returnValue = false;
                saveQueryScript()
            }
        }
    }

    onMounted(() => {
        window.addEventListener('keydown', handleEvent)
    });

    onUnmounted(() => {
        window.removeEventListener('keydown', handleEvent)
    });
    initParams()
</script>
<style  lang="scss">
    .console{
        width: 100%;
        height: 99vh;
        user-select: text;
        &-option{
            width: 100%;
            display: flex;
            justify-content: flex-start;
            &-item{
                margin: 3px 10px 2px 2px;
            }
        }
        &-tools{
            width: 100%;
            display: flex;
            justify-content: flex-start;
            border-bottom: 1px solid #DCDFE6;
            margin-left: 3px;
            &-item{
                border-left:  1px solid #DCDFE6
            }
        }
        &-edit{
            width: 100%;
        }
        &-data{
            width: 100%;
            &-tips{
                height: 24px;
                line-height: 24px;
                display: flex;
                justify-content: flex-start;
                font-size: 12px;
                div {
                    padding: 0 10px;
                    border-left: 1px solid #DCDFE6;
                    border-top: 1px solid #DCDFE6;
                }
            }
        }

    }

    :deep(.el-table) {
        --el-table-row-hover-bg-color: transparent;
        --el-table-header-bg-color: transparent;
        --el-table-header-text-color: #303133;
    }

    :deep(.el-table thead th) {
        font-weight: normal;
    }

</style>
